package com.boot.down.controller;

import com.boot.down.async.AsyncTask;
import com.boot.down.service.UserInfoService;
import com.boot.down.service.WebSocket;
import com.boot.down.util.JwtUtil;
import com.boot.down.vo.UserVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Future;

/**
 * @author Administrator
 */
@RestController
@RequestMapping("/user_info")
public class UserInfoController {

    @Resource
    private UserInfoService userInfoService;

    @Autowired
    private WebSocket webSocket;

    @Autowired
    private AsyncTask asyncTask;

    @GetMapping("/get")
    public List<UserVO> selectAll(){
        webSocket.sendMessage("发送相关信息");
        return userInfoService.selectAll();
    }

    @RequestMapping("/getVali")
    public Map<String, Object> getTokenValidata(@RequestParam String token){

        return JwtUtil.validataToken(token);
    }

    @GetMapping("/list")
    public ModelAndView list(Model model){

        model.addAttribute("userList", userInfoService.selectAll());
        model.addAttribute("title", "用户管理");
        return new ModelAndView("/user/form");
    }

    @RequestMapping("/add")
    public String addUserInfo(@RequestParam(name = "userName",defaultValue = "") String userName){

        return userInfoService.addUserInfo(userName);
    }

    /**
     * 测试异步
     * @return
     * @throws Exception
     */
    @RequestMapping("/asyncTask")
    public String asyncTest() throws Exception {

        long start = System.currentTimeMillis();
        Future<String> task1 = asyncTask.doTaskOne();
        Future<String> task2 = asyncTask.doTaskTwo();
        Future<String> task3 = asyncTask.doTaskThree();

        while (!task1.isDone() || !task2.isDone() || !task3.isDone()) {
            Thread.sleep(1000);
        }
        long end = System.currentTimeMillis();
        System.out.println("任务全部完成： 总耗时为：" + (end - start) + "毫秒");

        return "任务全部完成： 总耗时为：" + (end - start) + "毫秒";
    }
}
